package com.kaishengit.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kaishengit.entity.Project;
import com.kaishengit.entity.User;
import com.kaishengit.service.ProjectService;
import com.kaishengit.service.UserService;
import com.kaishengit.util.StringUtil;
import com.kaishengit.util.db.Page;
import com.kaishengit.util.web.ServletUtil;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String name = request.getParameter("username");
		String password = request.getParameter("password");
		
		UserService us = new UserService();
		 
		User u = us.login(name, password);
		
		if(u != null) {
			String p = request.getParameter("_p");
			
			int pageNum = 1;
			if(StringUtil.isNotEmpty(p)) {
				try {
					pageNum = Integer.parseInt(p);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}
			
			Page<Project> page = new ProjectService().findByUserIdAndPageNum(u.getId(),pageNum); 
			
			request.setAttribute("page", page);
			
			ServletUtil.setSessionAttribute(request, "curr_user", u);
			ServletUtil.forword(request, response, "main");
		} else {
			response.sendRedirect("error.jspx?state=10001");
		}
	}

}
